package com.guoli.sms.service.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import com.guoli.sms.dao.IDeptDao;
import com.guoli.sms.dao.impl.DeptDaoImpl;
import com.guoli.sms.service.IDeptService;
import com.guoli.sms.util.DBTool;
import com.guoli.sms.vo.Dept;

public class DeptServiceImpl implements IDeptService {
	
	private IDeptDao deptDao;
	private DBTool dbTool;
	
	public DeptServiceImpl(){
		deptDao = new DeptDaoImpl();
		dbTool = DBTool.newInstance();
	}
	
	@Override
	public List<Dept> getDepts() {
		Connection conn = dbTool.getConnection();
		List<Dept> depts = null;
		try {
			conn.setAutoCommit(false);
			depts = deptDao.getDepts(conn);
			conn.commit();
			conn.setAutoCommit(true);
		} catch (SQLException e) {
			try {
				conn.rollback();
				conn.setAutoCommit(true);
			} catch (SQLException e1) {
				System.out.println("回滚失败");
				e1.printStackTrace();
			}
			System.out.println("查询所有部门失败...");
			e.printStackTrace();
		}
		return depts;
	}

	@Override
	public Dept getDeptById(int id) {
		Connection conn = dbTool.getConnection();
		Dept dept = null;
		try {
			conn.setAutoCommit(false);
			dept = deptDao.getDeptById(id, conn);
			conn.commit();
			conn.setAutoCommit(true);
		} catch (SQLException e) {
			try {
				conn.rollback();
				conn.setAutoCommit(true);
			} catch (SQLException e1) {
				System.out.println("回滚失败");
				e1.printStackTrace();
			}
			System.out.println("通过ID查询部门失败...");
			e.printStackTrace();
		}
		return dept;
	}

	@Override
	public boolean addDept(String d_name) {
		Connection conn = dbTool.getConnection();
		boolean flag = false;
		try {
			conn.setAutoCommit(false);
			if(deptDao.getDeptByName(d_name, conn)!=-1){
				return flag;
			}
			deptDao.addDept(d_name, conn);
			conn.commit();
			conn.setAutoCommit(true);
			flag = true;
		} catch (SQLException e) {
			try {
				conn.rollback();
				conn.setAutoCommit(true);
			} catch (SQLException e1) {
				System.out.println("回滚失败");
				e1.printStackTrace();
			}
			System.out.println("添加部门失败...");
			e.printStackTrace();
		}
		return flag;
	}

}
